package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.base.Constants;
import com.jsbj.base.ResultBean;
import com.jsbj.enums.ConfigDictTypeEnum;
import com.jsbj.page.PageDomain;
import com.jsbj.page.TableSupport;
import com.jsbj.tools.BeanUtils;
import com.jsbj.tools.ChineseCharacterUtil;
import com.jsbj.tools.RequestHeaderUtils;
import com.jsbj.tools.StringUtils;
import com.jsbj.user.entities.*;
import com.jsbj.user.mapper.SysOrgMapper;
import com.jsbj.user.service.*;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 组织结构表（集团-公司-项目-标段） 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-03-07
 */
@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements ISysOrgService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ISysRoleOrgService sysRoleOrgService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysEquService sysEquService;

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysRoleTenantService sysRoleTenantService;
    @Autowired
    private ISysRoleUserService sysRoleUserService;

    @Override
    public List<SysOrg> getInfoByUserIdAndTenantCode(String userId, String tenantCode) {
        List<SysOrg> list = baseMapper.getInfoByUserIdAndTenantCode(userId, tenantCode);
        //查询单位类型
        List<SysDictData> dicDatas = sysDictDataService.getDataByKey("secType");
        for (SysOrg sysOrg : list) {
            for (SysDictData sysDictData : dicDatas) {
                if (sysOrg.getSecTypeValue().equals(sysDictData.getDicValue().toString())) {
                    sysOrg.setSecTypeDesc(sysDictData.getDicDesc());
                    continue;
                }
            }
        }
        return list;
    }

    @Override
    public List<SysOrg> getInfoByUserIdAndTenantCodeHomePage(String userId, String tenantCode, String data) {
        String systemCode = "";
        if(StringUtils.isNotEmpty(data)){
            JSONObject jsonObject = JSONObject.parseObject(data);
            systemCode = jsonObject.getString("systemCode");
        }

        List<SysOrg> list = new ArrayList<>();
        //试验系统显示检测单位   其他系统显示标段
        if(Constants.SYGLXT.equals(systemCode)){
            list = getTestUnitByUserIdAndTenantCode(userId,tenantCode,null);
        }else if (Constants.LWGLXT.equals(systemCode) || Constants.WLGLXT.equals(systemCode) || Constants.JDGLXT.equals(systemCode)) {
            list = getSGInfoByTenatCode(userId,tenantCode);
        } else if(Constants.STHBXT.equals(systemCode)){
            list = getSTHBInfoByTenatCode(userId,tenantCode);
        }else{
            list = getInfoByUserIdAndTenantCode(userId,tenantCode);
        }

        return list;
    }

    @Override
    public List<SysOrg> getInfoByUserIdAndTenantCodeEqu(String userId, String tenantCode) {

        List<SysOrg> list = getInfoByUserIdAndTenantCode(userId,tenantCode);
        //增加试验检测单位
        List<SysOrg> orgList = getTestUnitByUserIdAndTenantCode(userId, tenantCode, null);
        if(!orgList.isEmpty()){
            list.addAll(orgList);
        }

        return list;
    }

    @Override
    public List<SysOrg> getTestUnitByUserIdAndTenantCode(String userId, String tenantCode, String secType) {
        List<SysOrg> list = baseMapper.getTestUnitByUserIdAndTenantCode(userId, tenantCode, secType);
        //查询单位类型
        List<SysDictData> dicDatas = sysDictDataService.getDataByKey("secType");
        for (SysOrg sysOrg : list) {
            for (SysDictData sysDictData : dicDatas) {
                if (sysOrg.getSecTypeValue().equals(sysDictData.getDicValue().toString())) {
                    sysOrg.setSecTypeDesc(sysDictData.getDicDesc());
                    continue;
                }
            }
        }
        return list;
    }

    @Override
    public List<SysOrg> getTestUnitByUserIdAndTenantCodeAndOrgCode(String userId, String tenantCode, String orgCode) {

        List<SysOrg> list = baseMapper.getTestUnitByTenantCodeAndOrgCode( tenantCode, orgCode);
        return list;
    }

    @Override
    public SysOrg getInfoByOrgCode(String orgCode, String tenantCode) {
        LambdaQueryWrapper<SysOrg> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysOrg::getDisabled, 0);
        wrapper.eq(SysOrg::getOrgCode, orgCode);
        wrapper.eq(SysOrg::getTenantCode, tenantCode);
        wrapper.last(" limit 1 ");
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public List<SysOrg> getSGInfoByTenatCode(String userId, String tenantCode) {
        List<SysOrg> list = baseMapper.getSGInfoByTenatCode(userId, tenantCode);
        List<SysOrg> ret = new ArrayList<>();
        for (SysOrg sysOrg : list) {
            if ("5".equals(sysOrg.getOrgTypeValue()) && "3".equals(sysOrg.getSecTypeValue())) {
                List<SysOrg> childs = new ArrayList<>();
                for (SysOrg sysOrg1 : list) {
                    if ("6".equals(sysOrg1.getOrgTypeValue()) && sysOrg.getOrgCode().equals(sysOrg1.getParentOrgCode())) {
                        childs.add(sysOrg1);
                    }
                }
                sysOrg.setChilds(childs);
                ret.add(sysOrg);
            }
        }
        return ret;
    }

    @Override
    public List<SysOrg> getSTHBInfoByTenatCode(String userId, String tenantCode) {
        //用户拥有权限的环境监测标段
        Map<String,Object> params = new HashMap<>();
        params.put("tenantCode",tenantCode);
        params.put("userId",userId);
        params.put("equTypeValue", Constants.HJJC_CODE_ID);
        List<SysOrg> orgs = baseMapper.getByCondition(params);
        return orgs;
    }

    @Override
    public List<SysOrg> getListDataQxAll(String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);
        SysUser sysUser = sysUserService.getById(userId);

        JSONObject object = JSONObject.parseObject(inParam);
        String tenantCode = object.getString("tenantCode");

        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getDisabled, 0);
//        if ("0".equals(sysUser.getIsStatus())) {
//            queryWrapper.isNull(SysOrg::getParentOrgCode);
//        }

        if (StringUtils.isNotEmpty(tenantCode)) {
            SysTenant sysTenant = sysTenantService.getByTenantCode(tenantCode);
            if (null != sysTenant) {
                queryWrapper.eq(SysOrg::getTenantCode, tenantCode);
                if ("3".equals(sysTenant.getTenantTypeValue())) {
                    queryWrapper.and(wq->wq.eq(SysOrg::getOrgCode, tenantCode).or().isNull(SysOrg::getParentOrgCode));
                }
            }
        } else {
            // 查询所有有权限的租户
            // 如果角色id不为空，不能查询该用户自己创建的数据，只能查有权限的数据
            queryWrapper.and(wp -> wp.inSql(SysOrg::getTenantCode, "select a.tenant_code from sys_role_tenant a, sys_role_user b where " +
                    "a.disabled=0 and b.disabled=0 and a.role_id=b.role_id and b.user_id='"+userId+"'").or().eq(SysOrg::getCreaterId, userId));
        }
        List<String> orgCodeLs = new ArrayList<>();
        orgCodeLs = baseMapper.selectQXOrgCodeAndCreate(userId);
        List<String> finalOrgCodeLs = orgCodeLs;
        queryWrapper.and((wrapper) -> {
            wrapper.notIn(SysOrg::getParentOrgCode, finalOrgCodeLs).or().isNull(SysOrg::getParentOrgCode);
        });
        queryWrapper.and(wq->wq.in(SysOrg::getOrgCode, finalOrgCodeLs).or().eq(SysOrg::getCreaterId, userId));

        queryWrapper.orderByDesc(SysOrg::getCreateTime);
        List<SysOrg> sysOrgs = baseMapper.selectList(queryWrapper);
        Map<String, Object> tenantMap = new HashMap<>();
        for (SysOrg sysOrg : sysOrgs) {
            if (StringUtils.isNotEmpty(sysOrg.getOrgTypeValue())) {
                sysOrg.setOrgTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ORGTYPE.getCode(), sysOrg.getOrgTypeValue()));
            }
            if (StringUtils.isNotEmpty(sysOrg.getSecTypeValue())) {
                sysOrg.setSecTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.SECTYPE.getCode(), sysOrg.getSecTypeValue()));
            }
            List<SysOrg> child = getChildren(sysOrg.getOrgCode(), sysUser.getIsStatus(), orgCodeLs, sysOrg.getTenantCode(), tenantMap);
            // 如果是集团、公司、项目类型且在租户表已存在，不可删除
            SysTenant sysTenant1 = sysTenantService.getByTenantCode(sysOrg.getOrgCode());
            if (CollectionUtils.isEmpty(child) && null == sysTenant1) {
                sysOrg.setDel(true);
            } else {
                sysOrg.setDel(false);
                sysOrg.setChilds(child);
            }
            // 租户名称
            String tenantDesc = MapUtils.getString(tenantMap, sysOrg.getTenantCode(), "");
            if (StringUtils.isEmpty(tenantDesc)) {
                SysTenant sysTenant = sysTenantService.getByTenantCode(sysOrg.getTenantCode());
                if (null != sysTenant) {
                    tenantMap.put(sysOrg.getTenantCode(), sysTenant.getTenantName());
                }
            }
            sysOrg.setTenantDesc(MapUtils.getString(tenantMap, sysOrg.getTenantCode(), ""));
        }
        return sysOrgs;
    }

    @Override
    public List<SysOrg> getInfoByTenantCode(String tenantCode) {

        return baseMapper.selectList(Wrappers.<SysOrg>lambdaQuery()
                .eq(SysOrg::getTenantCode, tenantCode)
                .eq(SysOrg::getDisabled, 0));
    }

    @Override
    public IPage<SysOrg> getListData(String inParam) {
//        String tenantCode = RequestHeaderUtils.getTenantCode(request);

        // 如果不是超级管理员，只查询有权限的组织
        String userId = RequestHeaderUtils.getUserId(request);
        SysUser sysUser = sysUserService.getById(userId);

        JSONObject object = JSONObject.parseObject(inParam);
        String orgName = object.getString("orgName");
        String tenantCode = object.getString("tenantCode");
        String roleId = object.getString("roleId");

        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getDisabled, 0);
        if (StringUtils.isNotEmpty(roleId)) {
            queryWrapper.inSql(SysOrg::getId, "select org_id from sys_role_org where disabled=0 and role_id='"+roleId+"'");
        }
        if (StringUtils.isEmpty(orgName)) {
//            if ("0".equals(sysUser.getIsStatus())) {
//                queryWrapper.isNull(SysOrg::getParentOrgCode);
//            }
        } else {
            queryWrapper.like(SysOrg::getOrgName, orgName);
        }
        if (StringUtils.isNotEmpty(tenantCode)) {
//            orgCodeLs = baseMapper.selectQXOrgCode(userId);
            SysTenant sysTenant = sysTenantService.getByTenantCode(tenantCode);
            if (null != sysTenant) {
                queryWrapper.eq(SysOrg::getTenantCode, tenantCode);
                if ("3".equals(sysTenant.getTenantTypeValue())) {
                    queryWrapper.and(wq->wq.eq(SysOrg::getOrgCode, tenantCode).or().isNull(SysOrg::getParentOrgCode));
                }
            }
        } else {
//            orgCodeLs = baseMapper.selectQXOrgCodeAndCreate(userId);
            // 查询所有有权限的租户
            // 如果角色id不为空，不能查询该用户自己创建的数据，只能查有权限的数据
            queryWrapper.and(wp -> wp.inSql(SysOrg::getTenantCode, "select a.tenant_code from sys_role_tenant a, sys_role_user b where " +
                    "a.disabled=0 and b.disabled=0 and a.role_id=b.role_id and b.user_id='"+userId+"'").or().eq(SysOrg::getCreaterId, userId));
//            queryWrapper.inSql(SysOrg::getTenantCode, "select a.tenant_code from sys_role_tenant a, sys_role_user b where " +
//                    "a.disabled=0 and b.disabled=0 and a.role_id=b.role_id and b.user_id='"+userId+"'").or().eq(SysOrg::getCreaterId, userId);
        }
        List<String> orgCodeLs = new ArrayList<>();
        orgCodeLs = baseMapper.selectQXOrgCodeAndCreate(userId);
        List<String> finalOrgCodeLs = orgCodeLs;
        queryWrapper.and((wrapper) -> {
            wrapper.notIn(SysOrg::getParentOrgCode, finalOrgCodeLs).or().isNull(SysOrg::getParentOrgCode);
        });
        queryWrapper.and(wq->wq.in(SysOrg::getOrgCode, finalOrgCodeLs).or().eq(SysOrg::getCreaterId, userId));
        queryWrapper.orderByDesc(SysOrg::getCreateTime);

        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<SysOrg> page = new Page<>(pageNum, pageSize);
        IPage<SysOrg> iPage = baseMapper.selectPage(page, queryWrapper);

        Map<String, Object> tenantMap = new HashMap<>();
        for (SysOrg sysOrg : iPage.getRecords()) {
            if (StringUtils.isNotEmpty(sysOrg.getOrgTypeValue())) {
                sysOrg.setOrgTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ORGTYPE.getCode(), sysOrg.getOrgTypeValue()));
            }
            if (StringUtils.isNotEmpty(sysOrg.getSecTypeValue())) {
                sysOrg.setSecTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.SECTYPE.getCode(), sysOrg.getSecTypeValue()));
            }
            List<SysOrg> child = getChildren(sysOrg.getOrgCode(), sysUser.getIsStatus(), orgCodeLs, sysOrg.getTenantCode(), tenantMap);
            // 如果是集团、公司、项目类型且在租户表已存在，不可删除
            SysTenant sysTenant1 = sysTenantService.getByTenantCode(sysOrg.getOrgCode());
            if (CollectionUtils.isEmpty(child) && null == sysTenant1) {
                sysOrg.setDel(true);
            } else {
                sysOrg.setDel(false);
                if (StringUtils.isEmpty(orgName)) {
                    sysOrg.setChilds(child);
                }
            }
            // 租户名称
            String tenantDesc = MapUtils.getString(tenantMap, sysOrg.getTenantCode(), "");
            if (StringUtils.isEmpty(tenantDesc)) {
                SysTenant sysTenant = sysTenantService.getByTenantCode(sysOrg.getTenantCode());
                if (null != sysTenant) {
                    tenantMap.put(sysOrg.getTenantCode(), sysTenant.getTenantName());
                }
            }
            sysOrg.setTenantDesc(MapUtils.getString(tenantMap, sysOrg.getTenantCode(), ""));
        }
        return iPage;
    }

    @Override
    public ResultBean<JSONObject> saveOrUpdateData(SysOrg sysOrg) {
        // 校验必填
        if (StringUtils.isEmpty(sysOrg.getOrgCode()) || StringUtils.isEmpty(sysOrg.getOrgName()) || StringUtils.isEmpty(sysOrg.getOrgNuitName())
                || null == sysOrg.getSort() || StringUtils.isEmpty(sysOrg.getTenantCode()) || StringUtils.isEmpty(sysOrg.getOrgTypeValue())) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        if ("5".equals(sysOrg.getOrgTypeValue()) && StringUtils.isEmpty(sysOrg.getSecTypeValue())) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        sysOrg.setOrgTypeKey(ConfigDictTypeEnum.ORGTYPE.getCode());
        sysOrg.setSecTypeKey(ConfigDictTypeEnum.SECTYPE.getCode());
        // 校验编码是否重复
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getDisabled, 0);
        queryWrapper.eq(SysOrg::getTenantCode, sysOrg.getTenantCode());
        queryWrapper.eq(SysOrg::getOrgCode, sysOrg.getOrgCode());
        if (StringUtils.isNotEmpty(sysOrg.getId())) {
            queryWrapper.ne(SysOrg::getId, sysOrg.getId());
        }
        List<SysOrg> sysTenants = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(sysTenants)) {
            return new ResultBean<>().build("编码已存在，请重新填写！");
        }
        String userId = RequestHeaderUtils.getUserId(request);
        if (StringUtils.isEmpty(sysOrg.getId())) {
            sysOrg.setCreaterId(userId);
            sysOrg.setUpdateId(userId);
            baseMapper.insert(sysOrg);

            String roleIds = sysOrg.getRoleIds();
            if (StringUtils.isNotEmpty(roleIds)) {
                for (String roleId : roleIds.split(",")) {
                    SysRoleOrg sysRoleOrg = new SysRoleOrg();
                    sysRoleOrg.setRoleId(roleId);
                    sysRoleOrg.setOrgId(sysOrg.getId());
                    sysRoleOrg.setCreaterId(userId);
                    sysRoleOrg.setUpdateId(userId);
                    sysRoleOrgService.save(sysRoleOrg);
                }
            }


        } else {
            SysOrg updateInfo = baseMapper.selectById(sysOrg.getId());
            BeanUtils.copyPropertiesIgnoreNull(sysOrg, updateInfo);
            updateInfo.setUpdateId(userId);
            updateInfo.setUpdateTime(new Date());
            baseMapper.updateById(updateInfo);

            //先删除该组织下所有角色，再新增
            LambdaUpdateWrapper<SysRoleOrg> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SysRoleOrg::getDisabled, 0);
            updateWrapper.eq(SysRoleOrg::getOrgId, sysOrg.getId());
            SysRoleOrg sysRoleOrgD = new SysRoleOrg();
            sysRoleOrgD.setDisabled(1);
            sysRoleOrgD.setUpdateId(userId);
            sysRoleOrgD.setUpdateTime(new Date());
            sysRoleOrgService.update(sysRoleOrgD, updateWrapper);
            String roleIds = sysOrg.getRoleIds();
            if (StringUtils.isNotEmpty(roleIds)) {
                for (String roleId : roleIds.split(",")) {
                    SysRoleOrg sysRoleOrg = new SysRoleOrg();
                    sysRoleOrg.setRoleId(roleId);
                    sysRoleOrg.setOrgId(sysOrg.getId());
                    sysRoleOrg.setCreaterId(userId);
                    sysRoleOrg.setCreateTime(new Date());
                    sysRoleOrg.setUpdateId(userId);
                    sysRoleOrg.setUpdateTime(new Date());
                    sysRoleOrgService.save(sysRoleOrg);

                }
            }


        }
        // 处理超级管理员的角色组织权限
        String roleCode = "ROLE_SUPER_" + sysOrg.getTenantCode();
        // 查询id
        SysRole sysRole = sysRoleService.getByCode(roleCode);
        if (null == sysRole) {
            SysTenant sysTenant = sysTenantService.getByTenantCode(sysOrg.getTenantCode());
            // 插入新角色
            sysRole = new SysRole();
            sysRole.setRoleName(sysTenant.getTenantName() + "超管角色");
            sysRole.setRoleCode(roleCode);
            sysRole.setRoleType("1");
            sysRole.setSort(0);
            sysRole.setCreaterId(userId);
            sysRole.setCreateTime(new Date());
            sysRole.setUpdateId(userId);
            sysRole.setUpdateTime(new Date());
            sysRoleService.save(sysRole);
        }
        // 插入角色组织关系
        sysRoleOrgService.insertData(sysOrg.getId(), sysRole.getId(), userId);
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public ResultBean<JSONObject> saveOrUpdateDataEngineering(SysOrg sysOrg) {
        String userId = RequestHeaderUtils.getUserId(request);
        String orgCode = ChineseCharacterUtil.convertHanzi2Pinyin(sysOrg.getOrgName(), false);
        //查询组织编码是否重复
        // 校验编码是否重复
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getDisabled, 0);
        queryWrapper.eq(SysOrg::getTenantCode, sysOrg.getTenantCode());
        queryWrapper.eq(SysOrg::getOrgCode, orgCode);
        if (StringUtils.isNotEmpty(sysOrg.getId())) {
            queryWrapper.ne(SysOrg::getId, sysOrg.getId());
        }
        List<SysOrg> sysTenants = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(sysTenants)) {
            Random random = new Random();
            int ends = random.nextInt(99);
            //如果不足两位，前面补0
            orgCode = orgCode+String.format("%02d",ends);
        }
        sysOrg.setOrgCode(orgCode);
        sysOrg.setSort(0);
        sysOrg.setOrgTypeValue("5");
        ResultBean<JSONObject> result = saveOrUpdateData(sysOrg);

        return result;
    }

    @Override
    public IPage<Map<String,Object>> getOrgListPage(HttpServletRequest request, String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);
//        String tenantCode = RequestHeaderUtils.getTenantCode(request);
        JSONObject object = JSONObject.parseObject(inParam);
        String orgName = object.getString("orgName");
        String proCode = object.getString("proCode");

        /**
         * 分页条件
         */
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<Map<String,Object>> page = new Page<>(pageNum, pageSize);

        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("proCode",proCode);
//        params.put("tenantCode",tenantCode);
        params.put("orgName",orgName);
        IPage<Map<String,Object>> pages = baseMapper.getOrgListPage(page,params);

        return pages;
    }

    @Override
    public List<Map<String, Object>> getOrgListByUserIdAndOrgName(String inParam) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        String userId = RequestHeaderUtils.getUserId(request);
        JSONObject object = JSONObject.parseObject(inParam);
        String orgName = object.getString("orgName");
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("orgName",orgName);
        List<Map<String, Object>> proList = baseMapper.getTenantListByUserIdAndOrgName(params);
        if(proList==null || proList.size()<1){
            return null;
        }
        for(Map<String, Object> pro:proList){
            Map<String, Object> map = new HashMap<>();
            String proCode = MapUtils.getString(pro,"tenantCode");
            map.put("id",MapUtils.getString(pro,"id"));
            map.put("orgCode",proCode);
            map.put("orgName",MapUtils.getString(pro,"tenantName"));
            //查询组织列表
            params.put("proCode",proCode);
            List<Map<String, Object>> orgList = baseMapper.getOrgListByUserIdAndOrgName(params);
            map.put("orgList",orgList);
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public SysOrg getDetail(String id) {
        SysOrg sysOrg = baseMapper.selectById(id);
        if (StringUtils.isNotEmpty(sysOrg.getOrgTypeValue())) {
            sysOrg.setOrgTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ORGTYPE.getCode(), sysOrg.getOrgTypeValue()));
        }
        if (StringUtils.isNotEmpty(sysOrg.getSecTypeValue())) {
            sysOrg.setSecTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.SECTYPE.getCode(), sysOrg.getSecTypeValue()));
        }
        // 查询角色权限
        LambdaQueryWrapper<SysRoleOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleOrg::getDisabled, 0);
        queryWrapper.eq(SysRoleOrg::getOrgId, id);
        List<SysRoleOrg> sysRoleOrgs = sysRoleOrgService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(sysRoleOrgs)) {
            StringBuilder builder = new StringBuilder();
            StringBuilder builderName = new StringBuilder();
            List<String> ids = new ArrayList<>();
            for (SysRoleOrg sysRoleOrg : sysRoleOrgs) {
                builder.append(sysRoleOrg.getRoleId()).append(",");
                ids.add(sysRoleOrg.getRoleId());
            }
            sysOrg.setRoleIds(builder.substring(0, builder.length()-1));

            LambdaQueryWrapper<SysRole> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysRole::getDisabled, 0);
            queryWrapper1.in(SysRole::getId, ids);
            List<SysRole> sysRoles = sysRoleService.list(queryWrapper1);
            for (SysRole sysRole : sysRoles) {
                builderName.append(sysRole.getRoleName()).append(",");
            }
            sysOrg.setRoleNames(builderName.substring(0, builderName.length()-1));
        }
        if (StringUtils.isNotEmpty(sysOrg.getTenantCode())) {
            SysTenant sysTenant = sysTenantService.getByTenantCode(sysOrg.getTenantCode());
            if (null != sysTenant) {
                sysOrg.setTenantDesc(sysTenant.getTenantName());
            }
        }
        return sysOrg;
    }

    @Override
    public ResultBean<JSONObject> deleteData(String id) {
        SysOrg sysOrg = baseMapper.selectById(id);
        // 只有子节点可以删除
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getDisabled, 0);
        queryWrapper.eq(SysOrg::getParentOrgCode, sysOrg.getOrgCode());
        queryWrapper.last(" limit 1");
        if (null != baseMapper.selectOne(queryWrapper)) {
            return new ResultBean<>().build("当前节点非子节点，无法删除！");
        }
        sysOrg.setDisabled(1);
        String userId = RequestHeaderUtils.getUserId(request);
        sysOrg.setUpdateId(userId);
        sysOrg.setUpdateTime(new Date());
        baseMapper.updateById(sysOrg);
        // 删除组织角色表

        LambdaUpdateWrapper<SysRoleOrg> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysRoleOrg::getDisabled, 0);
        updateWrapper.eq(SysRoleOrg::getOrgId, id);
        SysRoleOrg sysRoleOrg = new SysRoleOrg();
        sysRoleOrg.setDisabled(1);
        sysRoleOrg.setUpdateId(userId);
        sysRoleOrg.setUpdateTime(new Date());
        sysRoleOrgService.update(sysRoleOrg, updateWrapper);



        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public List<SysOrg> getAllInfoByTenatCode(String userId, String tenantCode) {
        List<SysOrg> list = baseMapper.getInfoByUserIdAndTenantCode(userId, tenantCode);
        List<SysOrg> menulist = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            menulist.add(new SysOrg(list.get(i).getOrgCode(),
                    list.get(i).getParentOrgCode(),
                    list.get(i).getId(),
                    list.get(i).getOrgName(),
                    list.get(i).getDisabled()));
        }
        // 最后的结果
        List<SysOrg> result = buildTree(menulist, null);
        return result;
    }

    @Override
    public List<SysOrg> getOrgTreeByQx(String inParam) {
        // 如果不是超级管理员，只查询有权限的组织
        String userId = RequestHeaderUtils.getUserId(request);
//        String tenantCode = RequestHeaderUtils.getTenantCode(request);
        SysUser sysUser = sysUserService.getById(userId);

        JSONObject object = JSONObject.parseObject(inParam);
        String orgName = object.getString("orgName");
        String tenantCode = object.getString("tenantCode");

        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getDisabled, 0);
        if (StringUtils.isEmpty(orgName)) {
//            if ("0".equals(sysUser.getIsStatus())) {
//                queryWrapper.isNull(SysOrg::getParentOrgCode);
//            }
        } else {
            // 查询该名称匹配的租户编码
            List<String> nameOrgCodeLs = baseMapper.selectOrgCodeByName(orgName);
            if (CollectionUtils.isEmpty(nameOrgCodeLs)) {
                queryWrapper.eq(SysOrg::getId, "-1");
            } else {
                queryWrapper.and((wrapper) -> {
                    wrapper.notIn(SysOrg::getParentOrgCode, nameOrgCodeLs).or().isNull(SysOrg::getParentOrgCode);
                });
                queryWrapper.in(SysOrg::getOrgCode, nameOrgCodeLs);
            }
        }
        List<String> orgCodeLs = new ArrayList<>();
        if (!"0".equals(sysUser.getIsStatus())) {
            // 查询有权限的租户
            orgCodeLs = baseMapper.selectQXOrgCode(userId);
            List<String> finalOrgCodeLs = orgCodeLs;
            queryWrapper.and((wrapper) -> {
                wrapper.notIn(SysOrg::getParentOrgCode, finalOrgCodeLs).or().isNull(SysOrg::getParentOrgCode);
            });
            queryWrapper.in(SysOrg::getOrgCode, orgCodeLs);
        }
        if (StringUtils.isNotEmpty(tenantCode)) {
            SysTenant sysTenant = sysTenantService.getByTenantCode(tenantCode);
            if (null != sysTenant) {
                queryWrapper.eq(SysOrg::getTenantCode, tenantCode);
                if ("3".equals(sysTenant.getTenantTypeValue())) {
                    queryWrapper.and(wq->wq.eq(SysOrg::getOrgCode, tenantCode).or().isNull(SysOrg::getParentOrgCode));
                }
            }
        } else {
            // 查询所有有权限的租户
            queryWrapper.inSql(SysOrg::getTenantCode, "select a.tenant_code from sys_role_tenant a, sys_role_user b where " +
                    "a.disabled=0 and b.disabled=0 and a.role_id=b.role_id and b.user_id='"+userId+"'");
        }
        // 查询有权限租户最外层的节点

        queryWrapper.orderByDesc(SysOrg::getCreateTime);
        List<SysOrg> list = baseMapper.selectList(queryWrapper);
        Map<String, Object> tenantMap = new HashMap<>();
        for (SysOrg sysOrg : list) {
            // 租户名称
            String tenantDesc = MapUtils.getString(tenantMap, sysOrg.getTenantCode(), "");
            if (StringUtils.isEmpty(tenantDesc)) {
                SysTenant sysTenant = sysTenantService.getByTenantCode(sysOrg.getTenantCode());
                if (null != sysTenant) {
                    tenantMap.put(sysOrg.getTenantCode(), sysTenant.getTenantName());
                }
            }

            List<SysOrg> child = getChildren(sysOrg.getOrgCode(), sysUser.getIsStatus(), orgCodeLs, tenantCode, tenantMap);
            if (!CollectionUtils.isEmpty(child)) {
                sysOrg.setChilds(child);
            }
        }

        return list;
    }

    private List<SysOrg> buildTree(List<SysOrg> menulist, String pid) {
        List<SysOrg> resultList = new ArrayList<SysOrg>();
        if (CollectionUtils.isEmpty(menulist) || menulist.size() == 0) {
            return null;
        }
        for (SysOrg tree : menulist) {
            if(StringUtils.isEmpty(pid)){
                resultList.add(tree);
                tree.setChilds(buildTree(menulist, tree.getOrgCode()));
            }else {
                if (pid.equals(tree.getParentOrgCode())) {
                    resultList.add(tree);
                    tree.setChilds(buildTree(menulist, tree.getOrgCode()));
                }
            }
        }
        return resultList;
    }

    private List<SysOrg> getChildren(String orgCode, String isStatus, List<String> orgCodeLs, String tenantCode, Map<String, Object> tenantMap) {
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getDisabled, 0);
        queryWrapper.eq(SysOrg::getParentOrgCode, orgCode);
        if (StringUtils.isNotEmpty(tenantCode)) {
            SysTenant sysTenant = sysTenantService.getByTenantCode(tenantCode);
            if (null != sysTenant && "3".equals(sysTenant.getTenantTypeValue())) {
                queryWrapper.eq(SysOrg::getTenantCode, tenantCode);
            }
        }
        if (!"0".equals(isStatus)) {
            // 查询有权限的租户
            queryWrapper.in(SysOrg::getOrgCode, orgCodeLs);
        }
        List<SysOrg> child = baseMapper.selectList(queryWrapper);
        for (SysOrg sysOrg : child) {
            if (StringUtils.isNotEmpty(sysOrg.getOrgTypeValue())) {
                sysOrg.setOrgTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ORGTYPE.getCode(), sysOrg.getOrgTypeValue()));
            }
            if (StringUtils.isNotEmpty(sysOrg.getSecTypeValue())) {
                sysOrg.setSecTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.SECTYPE.getCode(), sysOrg.getSecTypeValue()));
            }
            List<SysOrg> child1 = getChildren(sysOrg.getOrgCode(), isStatus, orgCodeLs, sysOrg.getTenantCode(), tenantMap);
            // 如果是集团、公司、项目类型且在租户表已存在，不可删除
            SysTenant sysTenant1 = sysTenantService.getByTenantCode(sysOrg.getOrgCode());
            if (CollectionUtils.isEmpty(child) && null == sysTenant1) {
                sysOrg.setDel(true);
            } else {
                sysOrg.setDel(false);
                sysOrg.setChilds(child1);
            }

            // 租户名称
            String tenantDesc = MapUtils.getString(tenantMap, sysOrg.getTenantCode(), "");
            if (StringUtils.isEmpty(tenantDesc)) {
                SysTenant sysTenant = sysTenantService.getByTenantCode(sysOrg.getTenantCode());
                if (null != sysTenant) {
                    tenantMap.put(sysOrg.getTenantCode(), sysTenant.getTenantName());
                }
            }
            sysOrg.setTenantDesc(MapUtils.getString(tenantMap, sysOrg.getTenantCode(), ""));
        }
        return child;
    }
}
